import React, { Component } from 'react';
import { connect } from 'dva';
import { message, Modal, Pagination, Popconfirm, Button, Row, Col } from 'antd';
import styles from './../Users.css';
import moment from 'moment';
import Factory from '../../factory';
import * as datetime from '../../../utils/datetime'
import dataEditCreate from '../../addons/DataEdit'
import dataTableCreate from '../../addons/DataTable'
import DataEditTable from '../../addons/DataEditTable'
import * as menuService from '../../../services/menus';
import CompClieInfoBlDGForm from './CompClieInfoBlDGForm'
import CompClieInfoBlGrForm from './CompClieInfoBlGrForm'
import * as compDiviService from '../../../services/AccountDivi';
const daoName = "VCompClie";
const ButtonGroup = Button.Group;
const columns = [
  { title: '客户号', width: 150, sorter: true, key: 'CUNO', dataIndex: "CUNO", dispaly: true, filter: true },
  { title: '组织机构代码', width: 140, sorter: true, key: 'ENCD', dataIndex: "ENCD", dispaly: true, filter: true },
  { title: '客户名称', width: 250, sorter: true, key: 'CUNM', dataIndex: "CUNM", dispaly: true, filter: true },
  { title: '不良认定时间', width: 140, sorter: true, caption: 'RDSJ', key: 'RDSJ', render: data => datetime.format(data.RDSJ, "yyyy-MM-dd"), dispaly: true, filter: true },
  { title: '钢贸认定时间', width: 140, sorter: true, key: 'GMSJ', caption: 'GMSJ', render: data => datetime.format(data.GMSJ, "yyyy-MM-dd"), dispaly: true, filter: true },
  { title: '企业规模', width: 130, sorter: true, key: 'QYGM', dataIndex: "QYGM", dispaly: true, filter: true },
  { title: '存款余额', width: 130, sorter: true, key: 'ACBLS', dataIndex: "ACBLS", dispaly: true, filter: true },
  { title: '存款年日均', width: 130, sorter: true, key: 'YEALS', dataIndex: "YEALS", dispaly: true, filter: true },
  { title: '贷款余额', width: 130, sorter: true, dataIndex: 'ACBLL', key: 'ACBLL', dispaly: true, filter: true },
  { title: '贷款年日均', width: 130, sorter: true, key: 'YEALL', dataIndex: 'YEALL', dispaly: true, filter: true },
  { title: '是否不良', width: 130, sorter: true, dataIndex: 'BLCaption', key: 'ISBL', dispaly: true, filter: true },
  { title: '是否钢贸', width: 130, sorter: true, key: 'ISGM', dataIndex: 'GMCaption', dispaly: true, filter: true },
];
const controls = [
  { name: 'CUNO', required: true, type: 'text', label: '客户号', grid: 12 / 24 },
  { name: 'ENCD', required: true, type: 'text', label: '组织机构代码', grid: 12 / 24 },
  { name: 'CUNM', required: true, type: 'text', label: '客户名称', grid: 12 / 24 },
  { name: "RDSJ", label: "不良认定时间", type: "date", grid: 23 / 24, dataType: "date" },
  { name: "GMSJ", label: "钢贸认定时间", type: "date", grid: 23 / 24, dataType: "date" },
  { name: 'QYGM', required: true, type: 'text', label: '企业规模', grid: 12 / 24 },
  { name: 'ACBLS', required: true, type: 'number', label: '存款余额', grid: 12 / 24, dataType: "number" },
  { name: 'YEALS', required: true, type: 'number', label: '存款年日均', grid: 12 / 24, dataType: "number" },
  { name: 'ACBLL', required: true, type: 'number', label: '贷款余额', grid: 12 / 24, dataType: "number" },
  { name: 'YEALL', required: true, type: 'number', label: '贷款年日均', grid: 12 / 24, dataType: "number" },
  { name: "ISBL", label: "是否不良", required: true, data: [{ value: true, label: '是' }, { value: false, label: '否' }], grid: 12 / 24, type: "radio-group" },
  { name: "ISGM", label: "是否钢贸", required: true, data: [{ value: true, label: '是' }, { value: false, label: '否' }], grid: 12 / 24, type: "radio-group" },

]

const columnsUphmDivi = [
  { title: '客户名称', width: 215, sorter: true, dataIndex: 'CUNM', key: 'CUNM', dispaly: true, filter: true },
  { title: '组织机构代码', width: 140, sorter: true, dataIndex: 'ENCD', key: 'ENCD', dispaly: true, filter: true },
];
const controUphm = [
  { name: 'CUNM', required: true, type: 'text', label: '客户名称', grid: 12 / 24 },
  { name: 'ENCD', required: true, type: 'text', label: '组织机构代码', min: 1, max: 50, grid: 12 / 24 },
];
const columnsUpIndi = [
  { title: '客户名称', width: 215, sorter: true, dataIndex: 'NAME', key: 'NAME', dispaly: true, filter: true },
  { title: '证件号码', width: 140, sorter: true, dataIndex: 'IDNO', key: 'IDNO', dispaly: true, filter: true },
];
const controlsUpIndi = [
  { name: 'NAME', required: true, type: 'text', label: '客户名称', grid: 12 / 24 },
  { name: 'IDNO', required: true, type: 'text', label: '证件号码', min: 1, max: 50, grid: 12 / 24 },
];
const EditFrom = dataEditCreate(daoName);
const DataTable = dataTableCreate(daoName);
class CompClieInfoBlForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataChange: false,
      zhmData: {},
      isbl: -1,
      isgm: -1
    };
  }
  componentDidMount() {
    this.props.dispatch({
      type: `${daoName}/setKeyName`,
      payload: { keyName: "ID", permID: this.props.permID }
    });
    let whereItems = [];
    let WhereCauses = [];
    whereItems.push({
      FieldName: "ISBL",
      Operator: "=",
      FieldValues: '1'
    })
    whereItems.push({
      FieldName: "ISGM",
      Operator: "=",
      FieldValues: '1'
    })
    WhereCauses.push({
      WhereItems: whereItems,
      RelationSign: "OR"
    })
    let seeks = WhereCauses
    let sort = {
      field: 'RDSJ',
      order: 'descend'
    }
    this.props.dispatch({
      type: `${daoName}/fetch`,
      payload: { daoName, page: 1, pageSize: 10, seeks, sorter: sort }
    });
    this.loadOptionData();
  }
  loadOptionData() {
    let options = []
    controls.map(c => {
      if (c.fetch) {
        let f = c.fetch;
        if (c.type === 'cascader-select') {
          f.isCascader = true;
        }
        if (c.type !== 'search') {
          options.push(f);
        }
      }
    })
    if (daoName && options.length > 0) {
      this.props.dispatch({ type: `${daoName}/fetchOptions`, payload: { options } });
    }
  }
  showModelHandler(isAdd) {
    let key = null
    if (!isAdd) {
      const len = this.props.selectedRowKeys.length;
      if (len === 0) {
        message.info('请选择要编辑的行，如果选择了多行，则使用最后一次选择！');
        return;
      }
      key = this.props.selectedRowKeys[len - 1]
    }
    this.props.dispatch({
      type: `${daoName}/openEdit`,
      payload: { key }
    });
  }
  deleteHandler() {
    const keys = this.props.selectedRowKeys;
    const len = keys.length;
    if (len === 0) {
      message.info('请选择要删除的行！');
      return;
    }
    Modal.confirm({
      title: '提示',
      content: `你确认要删除选中的${len}行数据吗？`,
      okText: '删除',
      cancelText: '取消',
      onOk: () => {
        this.props.dispatch({
          type: `${daoName}/remove`,
          payload: { daoName, keys },
        });
      }
    });
  }
  edidOkHandler() {
    const form = this.refs.CompClieInfoBlForm.getForm()
    form.validateFields((err, values) => {
      if (!err) {
        let t = `${daoName}/create`
        const { keyName, record } = this.props;
        let msg = "数据添加成功！"
        if (record[keyName]) {
          values[keyName] = record[keyName];
          t = `${daoName}/patch`
          msg = "数据修改成功！"
        }
        controls.map((c, i) => {
          if (c.type === 'cascader-select') {
            let vs = values[c.name];
            if (vs.length > 0) {
              values[c.name] = vs[vs.length - 1];
            } else {
              values[c.name] = null;
            }
          }
          if (c.dataType === "number") {
            values[c.name] = Number(values[c.name])
          } else if (c.dataType === "date" || c.dataType === "datetime") {
            let date = !values[c.name] ? null : new Date(values[c.name])
            values[c.name] = !values[c.name] ? null : new Date(date.getFullYear(), date.getMonth(), date.getDate(), 8, 0, 0)
          } else {
            values[c.name] = values[c.name] === undefined ? null : values[c.name]
          }
          if (c.multiple || c.type === 'checkbox-group') {
            values[c.name] = values[c.name].join(',');
          }
        })
        this.state.dataChange = true;
        this.props.dispatch({
          type: t,
          payload: { daoName, values },
        })
      }
    });
  };
  hideEditHandler() {
    const form = this.refs.CompClieInfoBlForm.getForm();
    form.resetFields();
    if (this.state.dataChange) {
      this.props.dispatch({
        type: `${daoName}/reload`,
        payload: { daoName },
      });
      this.state.dataChange = false;
    }
    this.props.dispatch({
      type: `${daoName}/hideEdit`
    });
  };
  seachHandler(data) {
    this.state.zhmData = data;
  }
  UpdateCompClieIsbl(value) {
    let khid = this.state.zhmData.ID
    // if (khid === undefined) {
    //   value = ""
    //   message.error("请输入组织机构代码或客户名称")
    //   return
    // }
    this.state.isbl = Number(value);
    let date = new Date()
    let month = date.getMonth() + 1
    let RDSJ = date.getFullYear() + "-" + (month < 10 ? "0" + month : month) + "-" + "01";
    let BLGM = 1
    let ISZ = Number(value)
    let content = ISZ === 1 ? `你确认要将客户【${this.state.zhmData.CUNM}】认定为不良客户吗？` : `你确认要客户【${this.state.zhmData.CUNM}】正常客户吗？`
    // Modal.confirm({
    //   title: '提示',
    //   content: content,
    //   okText: '确定',
    //   cancelText: '取消',
    //   onOk: () => {
    //     compDiviService.UpCompClieblgm({ khid, RDSJ, BLGM, ISZ }).then(function (data) {
    //       if (data === "OK") {
    //         message.success("认定成功!")
    //       }
    //       let whereItems = [];
    //       let WhereCauses = [];
    //       whereItems.push({
    //         FieldName: "ISBL",
    //         Operator: "=",
    //         FieldValues: '1'
    //       })
    //       whereItems.push({
    //         FieldName: "ISGM",
    //         Operator: "=",
    //         FieldValues: '1'
    //       })
    //       WhereCauses.push({
    //         WhereItems: whereItems,
    //         RelationSign: "OR"
    //       })
    //       let seeks = WhereCauses
    //       let sort = {
    //         field: 'RDSJ',
    //         order: 'descend'
    //       }
    //       this.props.dispatch({
    //         type: `${daoName}/fetch`,
    //         payload: { daoName, page: 1, pageSize: 10, seeks, sorter: sort }
    //       });
    //       this.loadOptionData();
    //     }.bind(this))
    //   }
    // });

  }
  UpdateCompClieIsgm(value) {
    let khid = this.state.zhmData.ID
    // if (khid === undefined) {
    //   message.error("请输入组织机构代码或客户名称")
    //   return
    // }
    this.state.isgm = Number(value);
    let date = new Date()
    let month = date.getMonth() + 1
    let RDSJ = date.getFullYear() + "-" + (month < 10 ? "0" + month : month) + "-" + "01";
    let BLGM = 2
    let ISZ = Number(value)
    let content = ISZ === 1 ? `你确认要将客户【${this.state.zhmData.CUNM}】认定为钢贸客户吗？` : `你确认要将客户【${this.state.zhmData.CUNM}】认定为非钢贸客户吗？`
    // Modal.confirm({
    //   title: '提示',
    //   content: content,
    //   okText: '确定',
    //   cancelText: '取消',
    //   onOk: () => {
    //     compDiviService.UpCompClieblgm({ khid, RDSJ, BLGM, ISZ }).then(function (data) {
    //       if (data === "OK") {
    //         message.success("认定成功!")
    //       }
    //       let whereItems = [];
    //       let WhereCauses = [];
    //       whereItems.push({
    //         FieldName: "ISBL",
    //         Operator: "=",
    //         FieldValues: '1'
    //       })
    //       whereItems.push({
    //         FieldName: "ISGM",
    //         Operator: "=",
    //         FieldValues: '1'
    //       })
    //       WhereCauses.push({
    //         WhereItems: whereItems,
    //         RelationSign: "OR"
    //       })
    //       let seeks = WhereCauses
    //       let sort = {
    //         field: 'RDSJ',
    //         order: 'descend'
    //       }
    //       this.props.dispatch({
    //         type: `${daoName}/fetch`,
    //         payload: { daoName, page: 1, pageSize: 10, seeks, sorter: sort }
    //       });
    //       this.loadOptionData();
    //     }.bind(this))
    //   }
    // });

  }
  add() {
    let khid = this.state.zhmData.ID
    let isbl = this.state.isbl
    let isgm = this.state.isgm
    if (khid === undefined) {
      message.error("请输入组织机构代码或客户名称")
      return
    }
    if (isbl === -1) {
      message.error("请选择是否不良客户")
      return
    }
    if (isgm === -1) {
      message.error("请选择是否钢贸客户")
      return
    }
    let date = new Date()
    let month = date.getMonth() + 1
    let RDSJ = date.getFullYear() + "-" + (month < 10 ? "0" + month : month) + "-" + "01";
    Modal.confirm({
      title: '提示',
      content: `你确认要将客户【${this.state.zhmData.CUNM}】认定为不良客户吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        compDiviService.UpCompClieblgm({ khid, RDSJ, isbl, isgm }).then(function (data) {
          if (data === "OK") {
            message.success("认定成功!")
          }
          let whereItems = [];
          let WhereCauses = [];
          whereItems.push({
            FieldName: "ISBL",
            Operator: "=",
            FieldValues: '1'
          })
          whereItems.push({
            FieldName: "ISGM",
            Operator: "=",
            FieldValues: '1'
          })
          WhereCauses.push({
            WhereItems: whereItems,
            RelationSign: "OR"
          })
          let seeks = WhereCauses
          let sort = {
            field: 'RDSJ',
            order: 'descend'
          }
          this.props.dispatch({
            type: `${daoName}/fetch`,
            payload: { daoName, page: 1, pageSize: 10, seeks, sorter: sort }
          });
          this.loadOptionData();
        }.bind(this))
      }
    });


  }
  del() {
    const keys = this.props.selectedRowKeys
    if (keys.length <= 0) {
      message.error("请选择要处理的数据行！")
      return
    }
    Modal.confirm({
      title: '提示',
      content: `你确认要将客户在不良客户中删除吗？且一并删除该客户下所关联的所有客户。`,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        compDiviService.DelClieblgm({ khid: keys[0] }).then(function (data) {
          if (data === "OK") {
            message.success("删除成功!")
          }
          let whereItems = [];
          let WhereCauses = [];
          whereItems.push({
            FieldName: "ISBL",
            Operator: "=",
            FieldValues: '1'
          })
          whereItems.push({
            FieldName: "ISGM",
            Operator: "=",
            FieldValues: '1'
          })
          WhereCauses.push({
            WhereItems: whereItems,
            RelationSign: "OR"
          })
          let seeks = WhereCauses
          let sort = {
            field: 'RDSJ',
            order: 'descend'
          }
          this.props.dispatch({
            type: `${daoName}/fetch`,
            payload: { daoName, page: 1, pageSize: 10, seeks, sorter: sort }
          });
          this.loadOptionData();
        }.bind(this))
      }
    });
  }
  render() {
    let { showEdit, record, permID, popedomTypes, offsetHeight } = this.props
    let table1Height = (offsetHeight - 133) * 0.9 - 150
    const pTypes = popedomTypes[permID]
    let datas = []
    const controlsFilter = [];
    if (pTypes.indexOf("2") !== -1) {
      controlsFilter.push(
        { name: 'DGKH', required: false, type: 'search', label: '对公客户', grid: 10 / 24, layout: { labelSpan: 8, wrapperSpan: 15 }, fetch: { daoName: "CompClie", searchColumns: ['ENCD', 'CUNM'], optionTpl: 'CUNM', valueTpl: "ID", onSelect: this.seachHandler.bind(this), permID: permID }, placeholder: '请输入组织机构号码或客户名称' },
        {
          name: 'ISBL', required: false, type: 'select', dataType: "number", label: '是否不良', grid: 4 / 24, data: [{ value: '1', label: '是' }, { value: '0', label: '否' }], layout: { labelSpan: 12, wrapperSpan: 11 },
          onChange: this.UpdateCompClieIsbl.bind(this),
        },
        {
          name: 'ISGM', required: false, type: 'select', dataType: "number", label: '是否钢贸', grid: 4 / 24, data: [{ value: '1', label: '是' }, { value: '0', label: '否' }], layout: { labelSpan: 12, wrapperSpan: 11 },
          onChange: this.UpdateCompClieIsgm.bind(this),
        },
        {
          name: 'button', required: false, type: 'button-group', grid: 5 / 24,
          data: [
            { value: '1', label: '添加', onClick: this.add.bind(this) },
            // { value: '2', label: '修改', onClick: this.add.bind(this) },
            { value: '3', label: '删除', onClick: this.del.bind(this) }
          ]
        }
      )
    }
    return (
      <div className={styles.normal} style={{ background: '#fff', marginTop: -16, padding: '5px 5px' }}>
        <div>
          <div>
            <EditFrom ref="CompClieInfoBlForm" daoName={daoName} controls={controlsFilter} record={record} clearItemMargin={true} />
          </div>
          <DataTable ref="CompClieInfoBlTable" daoName={daoName} columns={columns} controls={controls} permID={permID} height={table1Height} />
          <div id="showCompDiviDiv" >
            <Row>
              <Col span={12}>
                <font style={{ fontSize: "18px", fontWeight: "bold" }}>【对公关联客户信息】</font>
                <CompClieInfoBlDGForm permID={permID} />
              </Col>
              <Col span={12}>
                <font style={{ fontSize: "18px", fontWeight: "bold" }}>【零售关联客户信息】</font>
                <CompClieInfoBlGrForm permID={permID} />
              </Col>
            </Row>
          </div>
        </div>
      </div>
    )
  }
}

function mapStateToProps(state) {
  const { showEdit, record, selectedRowKeys, keyName } = state[daoName];
  const { userID, orgID, pOrgID, popedomTypes, offsetHeight } = state.menus;
  return {
    userID,
    orgID,
    pOrgID,
    popedomTypes,
    showEdit,
    selectedRowKeys,
    keyName,
    record,
    offsetHeight
  }
}
CompClieInfoBlForm = connect(mapStateToProps)(CompClieInfoBlForm)
export default CompClieInfoBlForm;

let render = (props) => React.createElement(CompClieInfoBlForm, props);
let f = new Factory()
f.set("CompClieInfoBlForm", render)
